﻿<script lang="ts" setup name="tickets">
import { ref, reactive, onMounted } from 'vue';
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from 'element-plus';
import { downloadStreamFile } from '/@/utils/download';
import { useticketsApi } from '/@/api/ticket/tickets';
import { usetechnologicalprocessApi } from '/@/api/technology/technologicalprocess';
import editDialog from '/@/views/ticket/tickets/component/editDialog.vue';
import printDialog from '/@/views/system/print/component/hiprint/preview.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import ImportData from '/@/components/table/importData.vue';
import { number } from 'echarts';

const technologicalprocessApi = usetechnologicalprocessApi();
const ticketsApi = useticketsApi();
const printDialogRef = ref();
const editDialogRef = ref();
const importDataRef = ref();

const statetechnologicalprocess = reactive({
	exportLoading: false,
	tableLoading: false,
	stores: {},
	showAdvanceQueryUI: false,
	dropdownData: {} as any,
	selectData: [] as any[],
	tableQueryParams: {} as any,
	tableParams: {
		page: 1,
		pageSize: 20,
		total: 0,
		field: 'createTime', // 默认的排序字段
		order: 'descending', // 排序方向
		descStr: 'descending', // 降序排序的关键字符
	},
	tableData: [],
});
const state = reactive({
	exportLoading: false,
	tableLoading: false,
	stores: {},
	showAdvanceQueryUI: false,
	dropdownData: {} as any,
	selectData: [] as any[],
	tableQueryParams: {} as any,
	tableParams: {
		page: 1,
		pageSize: 20,
		total: 0,
		field: 'createTime', // 默认的排序字段
		order: 'descending', // 排序方向
		descStr: 'descending', // 降序排序的关键字符
	},
	tableData: [],
});

// 常见颜色数组
const commonColors = ['#409EFF', '#E6A23C', '#67C23A', '#F56C6C', '#909399'];

const progressItems = ref([]);

// 页面加载时
onMounted(async () => {
	const data = (await ticketsApi.getDropdownData(true).then((res) => res.data.result)) ?? {};
	state.dropdownData.masterId = data.masterId;
	state.dropdownData.productionId = data.productionId;
	state.dropdownData.processprogress = data.processprogress;
	await handleQuery();
});

// 查询操作
const handleQuery = async (params: any = {}) => {
	state.tableLoading = true;

	state.tableParams = Object.assign(state.tableParams, params);

	const result = await ticketsApi.page(Object.assign(state.tableQueryParams, state.tableParams)).then((res) => res.data.result);
	state.tableParams.total = result?.total;
	state.tableData = result?.items ?? [];

	state.tableLoading = false;
	console.log(state.tableData);
};

// 修改 handleQuerytechnologicalprocess 方法，接受动态的 processprogress 值作为参数
const handleQuerytechnologicalprocess = async (processProgress: string, params: any = {}) => {
	statetechnologicalprocess.tableQueryParams.technological_process_code = processProgress;
	statetechnologicalprocess.tableLoading = true;
	statetechnologicalprocess.tableParams = Object.assign(statetechnologicalprocess.tableParams, params);

	const result = await technologicalprocessApi.page(Object.assign(statetechnologicalprocess.tableQueryParams, statetechnologicalprocess.tableParams)).then((res) => res.data.result);
	statetechnologicalprocess.tableParams.total = result?.total;
	statetechnologicalprocess.tableData = statetechnologicalprocess.tableData.concat(result?.items ?? []);
	statetechnologicalprocess.tableLoading = false;

	return result?.items ?? [];
};

// 列排序
const sortChange = async (column: any) => {
	state.tableParams.field = column.prop;
	state.tableParams.order = column.order;
	await handleQuery();
};

// 删除
const deltickets = (row: any) => {
	ElMessageBox.confirm(`确定要删除吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await ticketsApi.delete({ id: row.id });
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 批量删除
const batchDeltickets = () => {
	ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await ticketsApi.batchDelete(state.selectData.map((u) => ({ id: u.id }))).then((res) => {
				ElMessage.success(`成功批量删除${res.data.result}条记录`);
				handleQuery();
			});
		})
		.catch(() => {});
};

// 导出数据
const exportticketsCommand = async (command: string) => {
	try {
		state.exportLoading = true;
		if (command === 'select') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map((u) => u.id) });
			await ticketsApi.exportData(params).then((res) => downloadStreamFile(res));
		} else if (command === 'current') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams);
			await ticketsApi.exportData(params).then((res) => downloadStreamFile(res));
		} else if (command === 'all') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
			await ticketsApi.exportData(params).then((res) => downloadStreamFile(res));
		}
	} finally {
		state.exportLoading = false;
	}
};

// 工序进度列显示逻辑
const processProgressFormatter = (row: any) => {
	return row.current_process || '无数据';
};

const dialogTableVisible = ref(false);

const form = reactive({
	name: '',
	region: '',
	date1: '',
	date2: '',
	delivery: false,
	type: [],
	resource: '',
	desc: '',
});

// 弹出框
const Progress_popup_box = async (row: any) => {
	dialogTableVisible.value = true;
	const data = await handleQuerytechnologicalprocess(row.processprogress);
	progressItems.value = data.map((item, index) => ({
		label: item.current_process,
		percentage: item.completion_status == 1 ? 0 : 100,
		// 这里使用了一个简单的颜色循环，你可以根据需要自定义颜色
		// 也可以使用其他颜色生成逻辑
		// 例如：根据进度百分比来决定颜色等
		color: commonColors[index % commonColors.length],
	}));
};
</script>
<template>
	<div class="tickets-container" v-loading="state.exportLoading">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
				<el-row>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
						<el-form-item label="关键字">
							<el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="类型">
							<g-sys-dict v-model="state.tableQueryParams.ticketstype" code="work _order _type" render-as="select" placeholder="请选择类型" clearable filterable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="产品主数据">
							<el-select clearable filterable v-model="state.tableQueryParams.masterId" placeholder="请选择产品主数据">
								<el-option v-for="(item, index) in state.dropdownData.masterId ?? []" :key="index" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="产线">
							<el-select clearable filterable v-model="state.tableQueryParams.productionId" placeholder="请选择产线">
								<el-option v-for="(item, index) in state.dropdownData.productionId ?? []" :key="index" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="状态">
							<el-input v-model="state.tableQueryParams.ticketsstates" clearable placeholder="请输入状态" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="数量">
							<el-input-number v-model="state.tableQueryParams.quantity" clearable placeholder="请输入数量" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="已完成数量">
							<el-input-number v-model="state.tableQueryParams.completedquantity" clearable placeholder="请输入已完成数量" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="进度">
							<el-input v-model="state.tableQueryParams.progress" clearable placeholder="请输入进度" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="计划开始时间">
							<el-date-picker
								type="daterange"
								v-model="state.tableQueryParams.planstarttimeRange"
								value-format="YYYY-MM-DD HH:mm:ss"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="计划结束时间">
							<el-date-picker
								type="daterange"
								v-model="state.tableQueryParams.planEndtimeRange"
								value-format="YYYY-MM-DD HH:mm:ss"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="实际开始时间">
							<el-date-picker
								type="daterange"
								v-model="state.tableQueryParams.actualstarttimeRange"
								value-format="YYYY-MM-DD HH:mm:ss"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="实际结束时间">
							<el-date-picker
								type="daterange"
								v-model="state.tableQueryParams.actualendtimeRange"
								value-format="YYYY-MM-DD HH:mm:ss"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="投入数量">
							<el-input-number v-model="state.tableQueryParams.inputquantity" clearable placeholder="请输入投入数量" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="良品数量">
							<el-input-number v-model="state.tableQueryParams.goodproductquantity" clearable placeholder="请输入良品数量" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="报废数量">
							<el-input-number v-model="state.tableQueryParams.scrapquantity" clearable placeholder="请输入报废数量" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="来源">
							<el-input v-model="state.tableQueryParams.source" clearable placeholder="请输入来源" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="源工单号">
							<el-input v-model="state.tableQueryParams.sourceticketnumber" clearable placeholder="请输入源工单号" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="备注">
							<el-input v-model="state.tableQueryParams.remark" clearable placeholder="请输入备注" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="是否允许跳工序">
							<el-input v-model="state.tableQueryParams.skipornot" clearable placeholder="请输入是否允许跳工序" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="工序进度">
							<el-select clearable filterable v-model="state.tableQueryParams.processprogress" placeholder="请选择工序进度">
								<el-option v-for="(item, index) in state.dropdownData.processprogress ?? []" :key="index" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="编码">
							<el-input v-model="state.tableQueryParams.encode" clearable placeholder="请输入编码" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
						<el-form-item>
							<el-button-group style="display: flex; align-items: center">
								<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'tickets:page'" v-reclick="1000"> 查询 </el-button>
								<el-button icon="ele-Refresh" @click="() => (state.tableQueryParams = {})"> 重置 </el-button>
								<el-button icon="ele-ZoomIn" @click="() => (state.showAdvanceQueryUI = true)" v-if="!state.showAdvanceQueryUI" style="margin-left: 5px"> 高级查询 </el-button>
								<el-button icon="ele-ZoomOut" @click="() => (state.showAdvanceQueryUI = false)" v-if="state.showAdvanceQueryUI" style="margin-left: 5px"> 隐藏 </el-button>
								<el-button type="danger" style="margin-left: 5px" icon="ele-Delete" @click="batchDeltickets" :disabled="state.selectData.length == 0" v-auth="'tickets:batchDelete'"> 删除 </el-button>
								<el-button type="primary" style="margin-left: 5px" icon="ele-Plus" @click="editDialogRef.openDialog(null, '新增工单管理')" v-auth="'tickets:add'"> 新增 </el-button>
								<el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportticketsCommand">
									<el-button type="primary" style="margin-left: 5px" icon="ele-FolderOpened" v-reclick="20000" v-auth="'tickets:export'"> 导出 </el-button>
									<template #dropdown>
										<el-dropdown-menu>
											<el-dropdown-item command="select" :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
											<el-dropdown-item command="current">导出本页</el-dropdown-item>
											<el-dropdown-item command="all">导出全部</el-dropdown-item>
										</el-dropdown-menu>
									</template>
								</el-dropdown>
								<el-button type="warning" style="margin-left: 5px" icon="ele-MostlyCloudy" @click="importDataRef.openDialog()" v-auth="'tickets:import'"> 导入 </el-button>
							</el-button-group>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<el-table
				:data="state.tableData"
				@selection-change="(val: any[]) => { state.selectData = val; }"
				style="width: 100%"
				v-loading="state.tableLoading"
				tooltip-effect="light"
				row-key="id"
				@sort-change="sortChange"
				border
			>
				<el-table-column type="selection" width="40" align="center" v-if="auth('tickets:batchDelete') || auth('tickets:export')" />
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column prop="encode" label="编码" show-overflow-tooltip />
				<el-table-column prop="ticketstype" label="类型" show-overflow-tooltip>
					<template #default="scope">
						<g-sys-dict v-model="scope.row.ticketstype" code="work _order _type" />
					</template>
				</el-table-column>
				<el-table-column prop="masterId" label="产品主数据" :formatter="(row: any) => row.masterFkDisplayName" show-overflow-tooltip />
				<el-table-column prop="productionId" label="产线" :formatter="(row: any) => row.productionFkDisplayName" show-overflow-tooltip />
				<el-table-column prop="ticketsstates" label="状态" show-overflow-tooltip>
					<template #default="scope">
						<el-tag v-if="scope.row.ticketsstates"> 已开工 </el-tag>
						<el-tag type="danger" v-else> 备料中 </el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="processprogress" label="工序进度" :formatter="processProgressFormatter" show-overflow-tooltip>
					<template #default="scope">
						<el-button type="primary" round @click="Progress_popup_box(scope.row)">工序进度</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="quantity" label="数量" show-overflow-tooltip />
				<el-table-column prop="completedquantity" label="已完成数量" show-overflow-tooltip />
				<el-table-column prop="progress" label="进度" show-overflow-tooltip width="300">
					<template #default="scope">
						<div class="demo-progress">
							<el-progress :percentage="parseInt(scope.row.progress.replace('%', ''))" />
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="planstarttime" label="计划开始时间" show-overflow-tooltip />
				<el-table-column prop="planEndtime" label="计划结束时间" show-overflow-tooltip />
				<el-table-column prop="actualstarttime" label="实际开始时间" show-overflow-tooltip />
				<el-table-column prop="actualendtime" label="实际结束时间" show-overflow-tooltip />
				<el-table-column prop="inputquantity" label="投入数量" show-overflow-tooltip />
				<el-table-column prop="goodproductquantity" label="良品数量" show-overflow-tooltip />
				<el-table-column prop="scrapquantity" label="报废数量" show-overflow-tooltip />
				<el-table-column prop="source" label="来源" show-overflow-tooltip />
				<el-table-column prop="sourceticketnumber" label="源工单号" show-overflow-tooltip />
				<el-table-column prop="remark" label="备注" show-overflow-tooltip />
				<el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip v-if="auth('tickets:update') || auth('tickets:delete')">
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary" @click="editDialogRef.openDialog(scope.row, '编辑工单管理')" v-auth="'tickets:update'"> 编辑 </el-button>
						<el-button icon="ele-Delete" size="small" text type="primary" @click="deltickets(scope.row)" v-auth="'tickets:delete'"> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:currentPage="state.tableParams.page"
				v-model:page-size="state.tableParams.pageSize"
				@size-change="(val: any) => handleQuery({ pageSize: val })"
				@current-change="(val: any) => handleQuery({ page: val })"
				layout="total, sizes, prev, pager, next, jumper"
				:page-sizes="[10, 20, 50, 100, 200, 500]"
				:total="state.tableParams.total"
				size="small"
				background
			/>
			<ImportData ref="importDataRef" :import="ticketsApi.importData" :download="ticketsApi.downloadTemplate" v-auth="'tickets:import'" @refresh="handleQuery" />
			<printDialog ref="printDialogRef" :title="'打印工单管理'" @reloadTable="handleQuery" />
			<editDialog ref="editDialogRef" @reloadTable="handleQuery" />
		</el-card>
	</div>

	<el-dialog
		v-model="dialogTableVisible"
		title="工序进度"
		style="width: auto"
		:close-on-click-modal="false"
		:before-close="
			(done) => {
				dialogTableVisible = false;
				done();
			}
		"
	>
		<div class="progress-container">
			<!-- 单个进度组件 -->
			<div v-for="item in progressItems" :key="item.label" class="progress-item">
				<!-- 圆形进度条 -->
				<el-progress type="circle" :percentage="item.percentage" :width="80" :stroke-width="8" :color="item.color" style="margin-left: 50px" />

				<!-- 连接短横线 -->
				<div class="connector-line" :style="{ backgroundColor: item.color }" style="margin-left: 50px"></div>

				<!-- 项目名称 -->
				<div class="label" style="margin-left: 50px">{{ item.label }}</div>
			</div>
		</div>
	</el-dialog>
</template>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

.demo-progress .el-progress--line {
	margin-bottom: 15px;
	max-width: 600px;
}

.demo-progress .el-progress--circle {
	margin-right: 15px;
}
</style>    
<style scoped>
.progress-container {
	display: flex;
	justify-content: space-around;
	align-items: center;
	padding: 20px;
	background: white;
	border-radius: 8px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.progress-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;
}

.connector-line {
	width: 60px;
	height: 2px;
	margin: 10px 0;
}

.label {
	font-size: 16px;
	color: #333;
	font-weight: 500;
}

/* 调整Element Plus默认样式 */
:deep(.el-progress__text) {
	font-size: 16px !important;
}
</style>    